<template>
    <div>
        <!--面包屑导航-->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>商品管理</el-breadcrumb-item>
            <el-breadcrumb-item>添加商品</el-breadcrumb-item>
        </el-breadcrumb>
        <el-card>
            <el-alert title="添加商品信息" type="info" show-icon :closable="false" center></el-alert>
            <el-steps :space="200" :active="stepActive - 0" finish-status="success" align-center>
                <el-step title="基本信息"></el-step>
                <el-step title="商品参数"></el-step>
                <el-step title="商品属性"></el-step>
                <el-step title="商品图片"></el-step>
                <el-step title="商品内容"></el-step>
                <el-step title="完成"></el-step>
            </el-steps>
            <el-form :model="newGoods" :rules="goodsRules" ref="goodsRef" label-width="100px" label-position="top">
                <el-tabs tab-position="left" v-model="stepActive" :before-leave="beforeTabLeave" @tab-click="tabClick">
                    <el-tab-pane label="基本信息" name="0">
                        <el-form-item label="商品名称" prop="goods_name">
                            <el-input v-model="newGoods.goods_name"></el-input>
                        </el-form-item>
                        <el-form-item label="商品价格" prop="goods_price">
                            <el-input v-model="newGoods.goods_price" type="number"></el-input>
                        </el-form-item>
                        <el-form-item label="商品重量" prop="goods_weight">
                            <el-input v-model="newGoods.goods_weight" type="number"></el-input>
                        </el-form-item>
                        <el-form-item label="商品数量" prop="goods_number">
                            <el-input v-model="newGoods.goods_number" type="number"></el-input>
                        </el-form-item>
                        <el-form-item label="商品分类" prop="goods_cat">
                            <el-cascader
                                v-model="newGoods.goods_cat"
                                :options="cateList"
                                :props="cateProps"
                                @change="cascaderChange"
                                clearable
                            ></el-cascader>
                        </el-form-item>
                    </el-tab-pane>
                    <el-tab-pane label="商品参数" name="1">
                        <el-form-item v-for="item in paramsData" :label="item.attr_name" :key="item.attr_id">
                            <el-checkbox-group v-model="item.attr_vals">
                                <el-checkbox
                                    :label="checkBox"
                                    v-for="(checkBox, i) in item.attr_vals"
                                    :key="i"
                                    border
                                ></el-checkbox>
                            </el-checkbox-group>
                        </el-form-item>
                    </el-tab-pane>
                    <el-tab-pane label="商品属性" name="2">
                        <el-form-item v-for="item in attrsData" :label="item.attr_name" :key="item.attr_id">
                            <el-input v-model="item.attr_vals"></el-input>
                        </el-form-item>
                    </el-tab-pane>
                    <el-tab-pane label="商品图片" name="3">
                        <el-upload
                            :action="uploadURL"
                            :on-preview="handlePreview"
                            :on-remove="handleRemove"
                            list-type="picture"
                            :headers="headersObj"
                            :on-success="handleSuccess"
                        >
                            <el-button size="small" type="primary">点击上传</el-button>
                            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
                        </el-upload>
                    </el-tab-pane>
                    <el-tab-pane label="商品内容" name="4">
                        <!--富文本编辑器组件-->
                        <quill-editor v-model="newGoods.goods_introduce"></quill-editor>
                        <el-button type="primary" class="btnAdd" @click="addGoods">提交商品</el-button>
                    </el-tab-pane>
                </el-tabs>
            </el-form>
        </el-card>
        <el-dialog title="提示" :visible.sync="dialogPreviewVisible">
            <img :src="previewPath" class="previewImg" />
        </el-dialog>
    </div>
</template>

<script>
import _ from 'lodash'
export default {
    data() {
        return {
            stepActive: '0',
            newGoods: {
                goods_name: '',
                goods_price: 0,
                goods_weight: 0,
                goods_number: 0,
                goods_cat: [],
                goods_introduce: '',
                pics: [],
                attrs: []
            },
            goodsRules: {
                goods_name: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
                goods_price: [{ required: true, message: '请输入商品价格', trigger: 'blur' }],
                goods_weight: [{ required: true, message: '请输入商品重量', trigger: 'blur' }],
                goods_number: [{ required: true, message: '请输入商品数量', trigger: 'blur' }],
                goods_cat: [{ required: true, message: '请选择商品分类', trigger: 'blur' }]
            },
            cateList: [],
            cateProps: {
                expandTrigger: 'hover',
                label: 'cat_name',
                value: 'cat_id'
            },
            paramsData: [],
            attrsData: [],
            uploadURL: 'http://127.0.0.1:8888/api/private/v1/upload',
            headersObj: {
                // 图片上传组件请求头
                Authorization: sessionStorage.getItem('token')
            },
            previewPath: '',
            dialogPreviewVisible: false
        }
    },
    created() {
        this.getCateList()
        if (this.$route.query.id) {
            let id = this.$route.query.id
            this.getGoodsInfo(id)
        }
    },
    methods: {
        async getCateList() {
            const { data: res } = await this.$http.get('categories')
            if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
            this.cateList = res.data
        },
        async getGoodsInfo(id) {
            // 查询商品详情并渲染
            const { data: res } = await this.$http.get('goods/' + id)
            if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
            let goodsInfo = res.data
            goodsInfo.goods_cat = goodsInfo.goods_cat.split(',').map(Number)
            this.newGoods.goods_name = goodsInfo.goods_name
            this.newGoods.goods_price = goodsInfo.goods_price.toString()
            this.newGoods.goods_weight = goodsInfo.goods_weight.toString()
            this.newGoods.goods_number = goodsInfo.goods_number.toString()
            this.newGoods.goods_cat = goodsInfo.goods_cat
            this.newGoods.goods_introduce = goodsInfo.goods_introduce
        },
        cascaderChange() {
            if (this.newGoods.goods_cat.length !== 3) {
                this.newGoods.goods_cat = []
            }
        },
        beforeTabLeave(nName, oName) {
            if (oName === '0' && this.newGoods.goods_cat.length !== 3) {
                this.$message.error('请先选择商品分类！')
                return false
            }
        },
        async tabClick() {
            if (this.stepActive === '1') {
                // 如果访问的是动态参数面板
                const { data: res } = await this.$http.get(`categories/${this.catId}/attributes`, {
                    params: { sel: 'many' }
                })
                if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
                res.data.forEach(item => {
                    item.attr_vals = item.attr_vals ? item.attr_vals.split(',') : []
                })
                this.paramsData = res.data
            } else if (this.stepActive === '2') {
                // 如果访问的是静态属性面板
                const { data: res } = await this.$http.get(`categories/${this.catId}/attributes`, {
                    params: { sel: 'only' }
                })
                if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
                this.attrsData = res.data
            }
        },
        handlePreview(file) {
            // 图片上传预览
            this.previewPath = file.response.data.url
            this.dialogPreviewVisible = true
        },
        handleRemove(file) {
            // 移除上传的图片
            const removePath = file.response.data.tmp_path
            // 找出pics数组中要移除这项的索引
            const i = this.newGoods.pics.findIndex(item => item.pic === removePath)
            this.newGoods.pics.splice(i, 1)
        },
        handleSuccess(res) {
            // 图片上传成功后把临时地址保存到表单pics属性中
            const picInfo = { pic: res.data.tmp_path }
            this.newGoods.pics.push(picInfo)
        },
        addGoods() {
            // 添加商品提交
            this.$refs.goodsRef.validate(async valid => {
                if (!valid) return this.$message.error('请输入必要的表单项')
                // lodash的cloneDeep(obj)方法可以深拷贝
                const form = _.cloneDeep(this.newGoods)
                form.goods_cat = form.goods_cat.join(',')
                // 处理动态参数和静态属性
                this.paramsData.forEach(item => {
                    const newParams = {
                        attr_id: item.attr_id,
                        attr_value: item.attr_vals.join(',')
                    }
                    this.newGoods.attrs.push(newParams)
                })
                this.attrsData.forEach(item => {
                    const newAttrs = {
                        attr_id: item.attr_id,
                        attr_value: item.attr_vals
                    }
                    this.newGoods.attrs.push(newAttrs)
                })
                form.attrs = this.newGoods.attrs
                if (this.$route.query.id) {
                    const { data: res } = await this.$http.put('goods/' + this.$route.query.id, form)
                    if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
                    this.$message.success(res.meta.msg)
                } else {
                    const { data: res } = await this.$http.post('goods', form)
                    if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
                    this.$message.success(res.meta.msg)
                }
                this.$router.push('/goods')
            })
        }
    },
    computed: {
        catId() {
            if (this.newGoods.goods_cat.length === 3) {
                return this.newGoods.goods_cat[2]
            }
            return null
        }
    }
}
</script>

<style lang="less" scoped>
.el-checkbox {
    margin: 0 10px 0 0 !important;
}
.previewImg {
    width: 100%;
    height: auto;
}
.btnAdd {
    margin-top: 15px;
}
</style>
